import {
    compose,
    createStore,
    combineReducers,
    applyMiddleware
} from 'redux';

// 中间件
import handleTransitions
    from 'redux-history-transitions';
import multi from 'redux-multi';
import thunk from 'redux-thunk';
import bed from './util/bed';
import ajax, {setToken} from './util/ajax';
import {login, getToken} from './login';
import global from './global';

setToken(getToken);

const middleware = [bed, ajax, multi, thunk];

// IE检测
import {
    Router,
    hashHistory,
    browserHistory
} from 'react-router';

let history = browserHistory;
// IE10以下不支持browserHistory
if (window.ActiveXObject) {
    history = hashHistory;
}

// 创建存储
const enhancer = [
    applyMiddleware(...middleware),
    handleTransitions(history)
];

if (global.debug) {
    const devTools = window.devToolsExtension;
    if (devTools) enhancer.push(devTools());
}

import {reducers} from './store';
const store = createStore(
    combineReducers({...reducers}),
    compose(...enhancer)
);

// 渲染路由
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import routes from './app/route';

const container = document.createElement('main');
document.body.appendChild(container);

const root = routes => (
    <Provider store={store}>
        <Router history={history} routes={routes}/>
    </Provider>
);

let reload;
if (module.hot) {
    const {AppContainer} = require('react-hot-loader');
    reload = routes => {
        render(
            <AppContainer>
                {root(routes)}
            </AppContainer>,
            container
        );
    };
    module.hot.accept('./app/route', () => {
        reload(require('./app/route').default);
    });
} else {
    reload = routes => {
        render(root(routes), container);
    };
}

reload(routes);

// 登录检查
login(history);
